package com.rfid.row.convertUtil;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class ParserXml {
	
	public static Map<String,Integer[]> map = new HashMap<String, Integer[]>();
	
	public ParserXml() throws IOException {
		map = this.parserXmlByDom4j();
	}
	
	public ParserXml(String fileName) throws Exception {
		map = this.parserXmlByDom4j(fileName);
	}
	
	private Map parserXmlByDom4j(String fileName) throws Exception{
		File inputXml=new File(fileName);   
		
		SAXReader saxReader = new SAXReader();   
		try {   
			Document document = saxReader.read(inputXml);   
			Element entry=document.getRootElement();
			String key = null;
			Integer[] areas = new Integer[2];
			int index = 0;
			System.out.println(entry.attributeValue("name"));
			for(Iterator<?> i = entry.elementIterator(); i.hasNext();){
				Element name = (Element) i.next();
				key = name.attributeValue("value");
				System.out.println(name.getName()+":"+name.attributeValue("value"));
				for(Iterator<?> j = name.elementIterator(); j.hasNext();){   
					Element node=(Element) j.next();
					areas[index] = Integer.parseInt(node.getText());
					index++;
					System.out.println(node.getName()+":"+node.getText());   
				} 
				map.put(key, areas);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
		}
		return map;
	}
	
	private Map parserXmlByDom4j() throws IOException {
		String path = this.getClass().getClassLoader().getResource("").getPath();
		String fileName = path+"/definePattern.xml";
		File inputXml=new File(fileName);
		System.out.println(inputXml.exists());
		SAXReader saxReader = new SAXReader();   
		try {   
			Document document = saxReader.read(inputXml);   
			Element entry=document.getRootElement();
			String key = null;
			Integer[] areas = new Integer[2];
			int index = 0;
			System.out.println(entry.attributeValue("name"));
			for(Iterator<?> i = entry.elementIterator(); i.hasNext();){
				Element name = (Element) i.next();
				key = name.attributeValue("value");
				System.out.println(name.getName()+":"+name.attributeValue("value"));
				for(Iterator<?> j = name.elementIterator(); j.hasNext();){   
					Element node=(Element) j.next();
					areas[index] = Integer.parseInt(node.getText());
					index++;
					System.out.println(node.getName()+":"+node.getText());   
				} 
				map.put(key, areas);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
		}
		return map;
	}
}
